package com.tsj.spzx.user.service.Impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tsj.spzx.user.openFeign.SMessageFeign;
import com.tsj.spzx.user.service.SMessageService;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SMessageServiceImpl implements SMessageService {

    private static final String SMS_CODE_KEY = "userMsgCode:";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SMessageFeign sMessageFeign;

    /**
     * 发送短信验证码
     * @param phone
     */
    @Override
    public void sendMessage(String phone) throws JsonProcessingException {
        /**
         * 在这里做测试，我们就不每次都去真正的发验证码了
         */
        final String existsCode = redisTemplate.opsForValue().get(SMS_CODE_KEY + phone);
        if (StringUtils.hasText(existsCode)){
            // 这说明redis中存在这个验证码,我们后续就不再调用api去发送了，（只是测试）
            System.out.println("redis中已存在,不再调用，测试足够了!");
            return;
        }

        /**
         * 实际开发
         */
        // 生成验证码
        String code = RandomStringUtils.randomNumeric(4);
        // 将验证码存入redis，并设置有效期
        redisTemplate.opsForValue().set(SMS_CODE_KEY + phone, code, 5, TimeUnit.MINUTES);
        // 发送验证码
        // 采用远程调用短信服务发送短信验证码
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("minute", 5);
        ObjectMapper mapper = new ObjectMapper();
        String param = mapper.writeValueAsString(map);


        String response = sMessageFeign.sendMessage(
                "APPCODE 6bd3723d3e5447b699d1ca0b73c4f1b5",
                param,
                phone,
                "2e65b1bb3d054466b82f0c9d125465e2",
                "908e94ccf08b4476ba6c876d13f084ad"
        );
        System.out.println("短信发送结果：" + response);
    }
}
